// 敌人类
class Enemy {
    constructor(x, y, type = ENEMY_TYPES.ZOMBIE) {
        this.x = x;
        this.y = y;
        this.type = type;
        this.id = Utils.generateUUID();
        
        // 根据类型设置属性
        this.setupType(type);
        
        // AI相关
        this.target = null;
        this.lastDirectionChange = 0;
        this.directionChangeInterval = 2000; // 2秒改变一次方向
        this.randomDirection = { x: 0, y: 0 };
        
        // 动画
        this.animationFrame = 0;
        this.animationSpeed = 0.1;
        
        // 状态
        this.isDead = false;
        this.deathAnimation = 0;
        this.deathAnimationDuration = 1000; // 1秒死亡动画
    }
    
    // 根据类型设置属性
    setupType(type) {
        // 从平衡配置获取敌人属性
        const enemyConfig = BALANCE_CONFIG.ENEMIES[type];
        if (enemyConfig) {
            this.health = enemyConfig.health;
            this.maxHealth = enemyConfig.health;
            this.damage = enemyConfig.damage;
            this.speed = enemyConfig.speed;
            this.size = enemyConfig.size;
            this.experienceValue = enemyConfig.experience;
        } else {
            // 默认值（如果配置文件中没有找到对应类型）
            this.health = 30;
            this.maxHealth = 30;
            this.damage = 10;
            this.speed = 1.5;
            this.size = 15;
            this.experienceValue = 10;
        }
        
        // 设置颜色（保持原有的颜色逻辑）
        switch(type) {
            case ENEMY_TYPES.ZOMBIE:
                this.color = '#8B4513';
                break;
            case ENEMY_TYPES.SKELETON:
                this.color = '#F5F5DC';
                break;
            case ENEMY_TYPES.GHOST:
                this.color = '#E6E6FA';
                break;
            case ENEMY_TYPES.BOSS:
                this.color = '#FF4500';
                break;
            default:
                this.color = '#8B4513';
        }
    }
    
    // 更新敌人状态
    update(deltaTime, player) {
        if (this.isDead) {
            this.updateDeathAnimation(deltaTime);
            return;
        }
        
        this.updateAI(deltaTime, player);
        this.updateAnimation(deltaTime);
        this.updateStatusEffects(deltaTime);
    }
    
    // 更新AI
    updateAI(deltaTime, player) {
        if (!player) return;
        
        // 寻找最近的目标（玩家、分身、小兵）
        let nearestTarget = player;
        let nearestDistance = Utils.distance(this.x, this.y, player.x, player.y);
        
        // 检查分身
        if (window.game && window.game.cloneManager) {
            window.game.cloneManager.clones.forEach(clone => {
                if (!clone.isDead) {
                    const distance = Utils.distance(this.x, this.y, clone.x, clone.y);
                    if (distance < nearestDistance) {
                        nearestTarget = clone;
                        nearestDistance = distance;
                    }
                }
            });
        }
        
        // 检查小兵
        if (window.game && window.game.minionManager) {
            window.game.minionManager.minions.forEach(minion => {
                if (!minion.isDead) {
                    const distance = Utils.distance(this.x, this.y, minion.x, minion.y);
                    if (distance < nearestDistance) {
                        nearestTarget = minion;
                        nearestDistance = distance;
                    }
                }
            });
        }
        
        // 追踪最近的目标
        this.target = nearestTarget;
        this.chasePlayer(nearestTarget);
        
        // 攻击逻辑
        this.updateAttack(deltaTime);
    }
    
    // 追踪玩家
    chasePlayer(target) {
        const angle = Utils.angle(this.x, this.y, target.x, target.y);
        const targetPos = Utils.getPositionFromAngle(this.x, this.y, angle, this.speed);
        
        this.x = targetPos.x;
        this.y = targetPos.y;
    }
    
    // 更新攻击
    updateAttack(deltaTime) {
        if (!this.target) return;
        
        const distance = Utils.distance(this.x, this.y, this.target.x, this.target.y);
        if (distance <= this.size + (this.target.size || 0)) {
            // 攻击目标
            if (this.target.takeDamage) {
                this.target.takeDamage(this.damage);
            }
        }
    }
    
    // 随机移动
    randomMovement(deltaTime) {
        this.lastDirectionChange += deltaTime;
        
        if (this.lastDirectionChange >= this.directionChangeInterval) {
            this.randomDirection.x = Utils.randomFloat(-1, 1);
            this.randomDirection.y = Utils.randomFloat(-1, 1);
            
            // 标准化方向向量
            const length = Math.sqrt(this.randomDirection.x ** 2 + this.randomDirection.y ** 2);
            if (length > 0) {
                this.randomDirection.x /= length;
                this.randomDirection.y /= length;
            }
            
            this.lastDirectionChange = 0;
        }
        
        this.x += this.randomDirection.x * this.speed * 0.5;
        this.y += this.randomDirection.y * this.speed * 0.5;
        
        // 边界检查（限制在世界范围内）
        this.x = Utils.clamp(this.x, this.size, GAME_CONFIG.WORLD_WIDTH - this.size);
        this.y = Utils.clamp(this.y, this.size, GAME_CONFIG.WORLD_HEIGHT - this.size);
    }
    
    // 更新动画
    updateAnimation(deltaTime) {
        this.animationFrame += this.animationSpeed * deltaTime;
        if (this.animationFrame >= 4) {
            this.animationFrame = 0;
        }
    }
    
    // 更新死亡动画
    updateDeathAnimation(deltaTime) {
        this.deathAnimation += deltaTime;
        if (this.deathAnimation >= this.deathAnimationDuration) {
            this.isDead = true;
        }
    }
    
    // 更新状态效果
    updateStatusEffects(deltaTime) {
        // 燃烧效果
        if (this.burningTimer > 0) {
            this.burningTimer -= deltaTime;
            this.takeDamage(this.burningDamage * deltaTime / 1000);
            
            // 显示燃烧效果
            if (window.uiManager) {
                window.uiManager.showDamageNumber(this.x, this.y - 20, this.burningDamage);
            }
        }
        
        // 减速效果
        if (this.slowTimer > 0) {
            this.slowTimer -= deltaTime;
            if (this.slowTimer <= 0 && this.originalSpeed !== undefined) {
                this.speed = this.originalSpeed; // 恢复速度
            }
        }
    }
    
    // 渲染敌人
    render(ctx) {
        if (this.isDead) {
            this.renderDeathAnimation(ctx);
            return;
        }
        
        ctx.save();
        
        // 使用精灵渲染敌人
        let spriteName = 'enemy_basic';
        switch(this.type) {
            case ENEMY_TYPES.ZOMBIE: spriteName = 'enemy_basic'; break;
            case ENEMY_TYPES.SKELETON: spriteName = 'enemy_fast'; break;
            case ENEMY_TYPES.GHOST: spriteName = 'enemy_tank'; break;
            case ENEMY_TYPES.BOSS: spriteName = 'enemy_tank'; break;
        }
        
        const enemySprite = window.spriteManager ? window.spriteManager.getSprite(spriteName) : null;
        if (enemySprite) {
            enemySprite.render(ctx, this.x, this.y, this.size * 2, this.size * 2);
        } else {
            // 备用渲染（圆形）
            ctx.fillStyle = this.color;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 1;
            ctx.stroke();
        }
        
        // 绘制生命值条（如果受伤）
        if (this.health < this.maxHealth) {
            this.renderHealthBar(ctx);
        }
        
        // 绘制敌人类型指示器
        ctx.fillStyle = '#ffffff';
        ctx.font = '10px Arial';
        ctx.textAlign = 'center';
        const typeSymbol = this.getTypeSymbol();
        ctx.fillText(typeSymbol, this.x, this.y + this.size + 15);
        
        ctx.restore();
    }
    
    // 渲染生命值条
    renderHealthBar(ctx) {
        const barWidth = this.size * 2;
        const barHeight = 4;
        const barX = this.x - barWidth / 2;
        const barY = this.y - this.size - 10;
        
        // 背景
        ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 生命值
        const healthPercentage = this.health / this.maxHealth;
        const healthWidth = barWidth * healthPercentage;
        
        ctx.fillStyle = healthPercentage > 0.5 ? '#00ff00' : healthPercentage > 0.25 ? '#ffff00' : '#ff0000';
        ctx.fillRect(barX, barY, healthWidth, barHeight);
        
        // 边框
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 1;
        ctx.strokeRect(barX, barY, barWidth, barHeight);
    }
    
    // 渲染死亡动画
    renderDeathAnimation(ctx) {
        const progress = this.deathAnimation / this.deathAnimationDuration;
        const alpha = 1 - progress;
        const scale = 1 + progress * 0.5;
        
        ctx.save();
        ctx.globalAlpha = alpha;
        ctx.translate(this.x, this.y);
        ctx.scale(scale, scale);
        
        // 绘制死亡效果
        ctx.fillStyle = '#ff0000';
        ctx.beginPath();
        ctx.arc(0, 0, this.size, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.restore();
    }
    
    // 获取类型符号
    getTypeSymbol() {
        switch(this.type) {
            case ENEMY_TYPES.ZOMBIE: return 'Z';
            case ENEMY_TYPES.SKELETON: return 'S';
            case ENEMY_TYPES.GHOST: return 'G';
            case ENEMY_TYPES.BOSS: return 'B';
            default: return '?';
        }
    }
    
    // 受到伤害
    takeDamage(damage) {
        this.health -= damage;
        this.health = Math.max(0, this.health);
        
        if (this.health <= 0) {
            this.die();
        }
        
        return this.health <= 0;
    }
    
    // 死亡
    die() {
        this.isDead = true;
        this.deathAnimation = 0;
        
        // 播放死亡音效
        if (window.game && window.game.sounds && window.game.sounds.enemyDeath) {
            window.game.soundGenerator.playSound(window.game.sounds.enemyDeath);
        }
        
        // 添加死亡粒子效果
        if (window.particleSystem) {
            window.particleSystem.addExplosion(this.x, this.y, this.color);
        }
        
        // 掉落经验
        if (window.game && window.game.itemSpawner) {
            window.game.itemSpawner.spawnExperienceFromEnemy(this);
        }
        
        // 直接给予玩家经验值
        if (window.game && window.game.player) {
            window.game.player.gainExperience(this.experienceValue);
        }
    }
    
    // 检查是否死亡
    isDead() {
        return this.isDead;
    }
    
    // 检查是否完成死亡动画
    isDeathAnimationComplete() {
        return this.isDead && this.deathAnimation >= this.deathAnimationDuration;
    }
    
    // 获取碰撞边界
    getBounds() {
        return {
            x: this.x - this.size,
            y: this.y - this.size,
            width: this.size * 2,
            height: this.size * 2
        };
    }
    
    // 检查与其他对象的碰撞
    collidesWith(other) {
        return Utils.circleCollision(
            this.x, this.y, this.size,
            other.x, other.y, other.size || other.radius || 0
        );
    }
    
    // 获取到玩家的距离
    getDistanceToPlayer(player) {
        return Utils.distance(this.x, this.y, player.x, player.y);
    }
}

// 敌人生成器类
class EnemySpawner {
    constructor() {
        this.enemies = [];
        this.spawnTimer = 0;
        this.spawnInterval = 300; // 0.3秒生成一个敌人，更快的生成速度
        this.maxEnemies = 200; // 大幅增加最大敌人数
        this.difficulty = 1;
        this.timeElapsed = 0;
        this.bossDefeated = false;
        this.stage = 1;
    }
    
    // 更新生成器
    update(deltaTime, player) {
        this.timeElapsed += deltaTime;
        this.updateDifficulty();
        this.updateSpawnTimer(deltaTime);
        this.updateEnemies(deltaTime, player);
        this.cleanupDeadEnemies();
        
        // 检查是否应该生成Boss
        if (!this.bossDefeated && this.timeElapsed > 60000 && this.enemies.length < this.maxEnemies * 0.8) {
            this.spawnBoss();
        }
    }
    
    // 更新难度
    updateDifficulty() {
        this.difficulty = 1 + Math.floor(this.timeElapsed / 20000); // 每20秒增加难度
        this.spawnInterval = Math.max(50, 300 - this.difficulty * 20); // 更快的生成速度
        this.maxEnemies = Math.min(300, 200 + this.difficulty * 20); // 更多敌人
    }
    
    // 更新生成计时器
    updateSpawnTimer(deltaTime) {
        this.spawnTimer += deltaTime;
        
        if (this.spawnTimer >= this.spawnInterval && this.enemies.length < this.maxEnemies) {
            this.spawnEnemy();
            this.spawnTimer = 0;
        }
    }
    
    // 生成敌人
    spawnEnemy() {
        const spawnSide = Math.floor(Math.random() * 4); // 0:上, 1:右, 2:下, 3:左
        let x, y;
        
        switch(spawnSide) {
            case 0: // 上
                x = Utils.randomInt(0, GAME_CONFIG.WORLD_WIDTH);
                y = -20;
                break;
            case 1: // 右
                x = GAME_CONFIG.WORLD_WIDTH + 20;
                y = Utils.randomInt(0, GAME_CONFIG.WORLD_HEIGHT);
                break;
            case 2: // 下
                x = Utils.randomInt(0, GAME_CONFIG.WORLD_WIDTH);
                y = GAME_CONFIG.WORLD_HEIGHT + 20;
                break;
            case 3: // 左
                x = -20;
                y = Utils.randomInt(0, GAME_CONFIG.WORLD_HEIGHT);
                break;
        }
        
        // 根据难度选择敌人类型
        const enemyType = this.selectEnemyType();
        const enemy = new Enemy(x, y, enemyType);
        
        this.enemies.push(enemy);
    }
    
    // 选择敌人类型
    selectEnemyType() {
        const rand = Math.random();
        
        if (this.difficulty >= 5 && rand < 0.1) {
            return ENEMY_TYPES.BOSS;
        } else if (this.difficulty >= 3 && rand < 0.3) {
            return ENEMY_TYPES.GHOST;
        } else if (this.difficulty >= 2 && rand < 0.6) {
            return ENEMY_TYPES.SKELETON;
        } else {
            return ENEMY_TYPES.ZOMBIE;
        }
    }
    
    // 生成Boss
    spawnBoss() {
        const side = Math.floor(Math.random() * 4);
        let x, y;
        
        switch(side) {
            case 0: // 上边
                x = Math.random() * GAME_CONFIG.WORLD_WIDTH;
                y = -50;
                break;
            case 1: // 右边
                x = GAME_CONFIG.WORLD_WIDTH + 50;
                y = Math.random() * GAME_CONFIG.WORLD_HEIGHT;
                break;
            case 2: // 下边
                x = Math.random() * GAME_CONFIG.WORLD_WIDTH;
                y = GAME_CONFIG.WORLD_HEIGHT + 50;
                break;
            case 3: // 左边
                x = -50;
                y = Math.random() * GAME_CONFIG.WORLD_HEIGHT;
                break;
        }
        
        const boss = new Enemy(x, y, ENEMY_TYPES.BOSS);
        this.enemies.push(boss);
        this.bossDefeated = false;
        
        // 显示Boss出现提示
        if (window.uiManager) {
            window.uiManager.showMessage('Boss出现了！', 3000);
        }
    }
    
    // 更新所有敌人
    updateEnemies(deltaTime, player) {
        this.enemies.forEach(enemy => enemy.update(deltaTime, player));
    }
    
    // 清理死亡的敌人
    cleanupDeadEnemies() {
        this.enemies = this.enemies.filter(enemy => {
            if (enemy.isDeathAnimationComplete()) {
                // 检查是否是Boss死亡
                if (enemy.type === ENEMY_TYPES.BOSS) {
                    this.onBossDefeated();
                }
                return false;
            }
            return true;
        });
    }
    
    // Boss击败后的处理
    onBossDefeated() {
        this.bossDefeated = true;
        this.stage++;
        
        // 显示阶段升级提示
        if (window.uiManager) {
            window.uiManager.showMessage(`进入第${this.stage}阶段！敌人更加强大！`, 5000);
        }
        
        // 增加难度
        this.difficulty += 2;
        this.spawnInterval = Math.max(30, this.spawnInterval - 50); // 更快的生成
        this.maxEnemies = Math.min(400, this.maxEnemies + 50); // 更多敌人
        
        // 重置Boss状态，为下一个Boss做准备
        setTimeout(() => {
            this.bossDefeated = false;
        }, 30000); // 30秒后可以再次生成Boss
    }
    
    // 渲染所有敌人
    render(ctx) {
        this.enemies.forEach(enemy => enemy.render(ctx));
    }
    
    // 获取所有敌人
    getEnemies() {
        return this.enemies;
    }
    
    // 重置生成器
    reset() {
        this.enemies = [];
        this.spawnTimer = 0;
        this.difficulty = 1;
        this.timeElapsed = 0;
    }
} 